package oldreturn

import (
	"fmt"
	"net/http"
	"sync"

	"oldReturn/src/httpserver"
	"oldReturn/src/tools/cache"

	"github.com/gin-gonic/gin"
)

const (
	// NoJoin 未参加活动
	NoJoin = 0

	// IsJoin 已参加活动
	IsJoin = 1
)

func init() {
	err := httpserver.Register("/JoinAct", CP)
	if err != nil {
		fmt.Println(err)
	}
	GMap = &CPMap{
		sync.Mutex{},
		make(map[string]chan *gin.Context),
	}
}

var GMap *CPMap

type CPMap struct {
	Mx      sync.Mutex
	WorkMap map[string]chan *gin.Context
}

func CP(c *gin.Context) {
	GMap.Mx.Lock()
	defer GMap.Mx.Unlock()
	key := c.Query("UserId")
	if _, ok := GMap.WorkMap[key]; !ok {
		work := make(chan *gin.Context, 1)
		GMap.WorkMap[key] = work
		GMap.WorkMap[key] <- c
	} else {
		GMap.WorkMap[key] <- c
	}

	JoinAct(<-GMap.WorkMap[c.Query("UserId")])
}

var JoinAct = func(c *gin.Context) {
	var userRequests UserParam
	if err := c.ShouldBindJSON(&userRequests); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误！"})
		return
	}
	isold, isjoin, err := CheckUserIsOld(userRequests)
	if err != nil {
		fmt.Println(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "系统错误！"})
		return
	}
	if isold {
		if isjoin == IsJoin {
			c.JSON(http.StatusOK, gin.H{"joinact": false, "message": "已经参加过该活动！"})
		} else {
			err := SetUserJoinAct(userRequests.UserId, userRequests.PartnerId)

			userCache := cache.GetCacheManager()
			userCache.C.Delete(userRequests.UserId)

			if err != nil {
				fmt.Println(err)
				c.JSON(http.StatusInternalServerError, gin.H{"error": "系统错误！"})
				return
			}
			c.JSON(http.StatusOK, gin.H{"joinact": true, "message": "参加成功！"})
		}
	} else if !isold {
		c.JSON(http.StatusOK, gin.H{"joinact": false, "message": "不满足条件！"})
	}
}
